const mysql = require('mysql')
const qs = require('querystringify')
const setting = require('../setting.js')

const pool = mysql.createPool({
  connectionLimit: 5,
  host: setting.host,
  user: setting.user,
  password: setting.password,
  database: setting.database
})

class Db {
  handleError(err) {
    console.error(err)
  }
  connect() {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {
        if (err) {
          reject(err)
        } else {
          resolve(connection)
        }
      })
    }).catch(this.handleError)
  }
  query(sql, values) {
    // return new Promise((resolve, reject) => {
    //   pool.getConnection((err, connection) => {
    //     if (err) {
    //       reject(err)
    //     }
    //     connection.query(sql, values, (err, rows) => {
    //       connection.release()
    //       if (err) {
    //         reject(err)
    //       } else {
    //         console.log(sql, rows)
    //         resolve(rows)
    //       }
    //     })
    //   })
    // }).catch(this.handleError)
    
    return this.connect().then(connection => {
      return new Promise((resolve, reject) => {
        connection.query(sql, values, (err, rows) => {
          connection.release()
          console.log(sql)
          if (err) {
            console.log(err)
            reject(err)
          } else {
            console.log(rows)
            resolve(rows)
          }
        })
      }).catch(this.handleError)
    }).catch(this.handleError)
  }
  getSql(query) {
    let whereStr = '', limit = '', q = {}
    if (query.page && query.page_size) {
      let rows = +query.page_size
      let start = (+query.page - 1) * rows
      limit = ` limit ${start},${rows}`
    }
    for (const key in query) {
      if (query.hasOwnProperty(key) && key !== 'page' && key !== 'page_size') {
        const element = query[key];
        q[key] = element
      }
    }
    whereStr = qs.stringify(q, 'AND ').replace(/&/g, ' AND ').replace(/=/g, ' = ')
    return {
      whereStr,
      limit
    }
  }
}

module.exports = Db